package com.zhugang.week05;

/**
 * @program algorithms
 * @description: searchMaxtrix
 * @author: chanzhugang
 * @create: 2022/07/06 15:44
 */
public class SearchMatrix {

    /**
     * 74 搜索二维矩阵aw
     *
     * @param matrix
     * @param target
     * @return
     */
    public boolean searchMatrix(int[][] matrix, int target) {
        // 二维转一维(难度降低)，二分查找
        int m = matrix.length;
        int n = matrix[0].length;
        int low = 0;
        int high = m * n - 1;
        while (low <= high) {
            int mid = low + (high - low) / 2;
            int midValue = matrix[mid / n][mid % n];
            if (midValue == target) {
                return true;
            } else if (midValue < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }
        return false;
    }
}